package com.mh.common;

import com.mh.dto.bo.SuccessPayMQBo;
import com.mh.dto.bo.UseCouponBo;
import com.mh.pojo.CouponUse;
import com.mh.pojo.OrderInfos;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * Date:2024/10/26
 * author:zmh
 * description:RabbitMQ消息监听器
 */


@Component
@RequiredArgsConstructor
@Slf4j
public class RabbitMessageListener {

    private final MongoTemplate mongoTemplate;

    private final RabbitTemplate rabbitTemplate;

    /**
     * 创建预支付订单，并发送一个15分钟（订单过期）的延迟消息。
     */
    @RabbitListener(queues = "prePayOrder")
    public void createPrePayOrder(OrderInfos orderInfos){
        // 补充订单的一些固定参数
        orderInfos.setCreateTime(LocalDateTime.now().toString());
        orderInfos.setOrderStatus(0); // 订单状态【0 - 待支付】
        // 保存订单到mongodb
        mongoTemplate.save(orderInfos);

        // 发送一个15分钟的延迟消息
        int delayInMillis = 15 * 60 * 1000; // 15 分钟
        rabbitTemplate.convertAndSend("delayed.exchange", "delayed.queue", orderInfos, message -> {
            message.getMessageProperties().setHeader("x-delay", delayInMillis);
            return message;
        });
    }

    /**
     *  检查订单是否支付，如果未支付则取消
     * @param orderInfos ·
     */
    @RabbitListener(queues = "delayed.queue")
    public void cancelPrePayOrder(OrderInfos orderInfos){
        // 检查查订单状态
        Query query = new Query().addCriteria(Criteria.where("orderId").is(orderInfos.getOrderId()));
        OrderInfos order = mongoTemplate.findOne(query, OrderInfos.class);
        if (order != null && order.getOrderStatus() == 0) {
            // 订单未支付，取消订单
            Update update = new Update();
            update.set("orderStatus", 5);
            mongoTemplate.updateFirst(query, update, OrderInfos.class);

        }
    }

    /**
     * 微信支付成功回调处理
     * @param successPayMQBo 需要的参数对象，包含微信支付成功订单号和系统内部订单号
     */
    @RabbitListener(queues = "successPay")
    public void successPay(SuccessPayMQBo successPayMQBo){
        // 查询出订单信息
        Query query = new Query().addCriteria(Criteria.where("orderId").is(successPayMQBo.getOut_trade_no()));
        OrderInfos order = mongoTemplate.findOne(query, OrderInfos.class);
        if (order != null) {
            // 更新订单状态为已支付
            Update update = new Update();
            update.set("orderStatus", 1);
            update.set("wxPayId", successPayMQBo.getWxSuccessPayId());
            mongoTemplate.updateFirst(query, update, OrderInfos.class);

            log.info("订单{}支付成功", successPayMQBo.getOut_trade_no());
        }
    }

    /**
     * 使用优惠券，创建优惠券使用记录信息
     */
    @RabbitListener(queues = "useCoupon")
    public void cancelPay(UseCouponBo  useCouponBo) {
        // 创建一条使用记录，并保存
        CouponUse couponUse = new CouponUse(useCouponBo.getUserId(), useCouponBo.getCouponId(), LocalDateTime.now().toString());
        mongoTemplate.save(couponUse);
    }

}
